import logging

from flask import Blueprint, request
from flask import jsonify

from airflow.patsnap.store.resource_sync import S3Resource
from airflow.exceptions import AirflowException

log = logging.getLogger(__name__)

api_speech_file = Blueprint('api_speech_file', __name__)


# user route
@api_speech_file.route('/files', methods=['GET'])
def get_files():
    path = request.args.get('path', "", type=str)
    try:
        result = S3Resource.list_file(S3Resource(), path)
        return jsonify(code=0, message='ok', data=result)
    except AirflowException as e:
        log.error("get_files error =%s, params=%s", e, path)
        return jsonify(code=500, message=str(e), data=None)


# user route
@api_speech_file.route('/files', methods=['DELETE'])
def delete_files():
    path = request.args.get('path', "", type=str)
    try:
        S3Resource.delete_file(S3Resource(), path)
        return jsonify(code=0, message='ok', data=None)
    except AirflowException as e:
        log.error("delete_files error =%s, params=%s", e, path)
        return jsonify(code=500, message=str(e), data=None)


@api_speech_file.route('/files/upload', methods=['POST'])
def upload_files():
    path = request.form.get('path', "", type=str)
    size = request.form.get('size', type=int)
    file = request.files.get('file')
    try:
        S3Resource.upload_file(S3Resource(), path, file, size)
        return jsonify(code=0, message='ok', data=None)
    except AirflowException as e:
        log.error("delete_files error =%s, params=%s", e, path)
        return jsonify(code=500, message=str(e), data=None)


@api_speech_file.route('/files/download', methods=['GET'])
def download_files():
    path = request.args.get('path', "", type=str)
    try:
        return S3Resource.download_file(S3Resource(), path, )
        # return jsonify(code=0, message='ok', data=None)
    except AirflowException as e:
        log.error("download_files error =%s, params=%s", e, path)
        return jsonify(code=500, message=str(e), data=None)
